<template>
  <div id="emoji"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, useAttrs } from 'vue';
import Picker from 'emoji-picker-element/picker';
import Database from 'emoji-picker-element/database';
import ZH from 'emoji-picker-element/i18n/zh_CN';
import example from 'emoji-picker-element-data/zh/emojibase/data.json?url';

const props = defineProps({
  mode: {
    type: String,
    default: 'light',
    validator: (value) => ['light', 'dark'].includes(value),
  },
  width: {
    type: [String, Number],
    default: '350px',
  },
  height: {
    type: [String, Number],
    default: '350px',
  },
  i18n: {
    type: Object,
    default: ZH,
  },
  locale: {
    type: String,
    default: 'zh',
  },
  dataSource: {
    type: String,
    default: example,
  },
  customEmoji: {
    type: Object,
    default: () => [],
  },
  emojiVersion: {
    type: String,
    default: '',
  },
  skinToneEmoji: {
    type: String,
    default: '🖐️',
  },
  customCategorySorting: {
    type: Function,
    default: () => { },
  },
  isDataBase: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['change', 'skinToneChange']);

const database = ref(null);
const emojiPickerRef = ref(null);

const attrs = useAttrs()

const handleEmojiClick = (event) => {
  emit('change', event.detail.emoji);
};

const handleSkinChange = (event) => {
  emit('skinToneChange', event.detail);
};

onMounted(() => {
  const picker = new Picker({
    i18n: props.i18n,
    locale: props.locale,
    mode: props.mode,
    width: props.width,
    height: props.height,
    dataSource: props.dataSource,
    customEmoji: props.customEmoji,
    emojiVersion: props.emojiVersion,
    skinToneEmoji: props.skinToneEmoji,
    customCategorySorting: props.customCategorySorting,
  });

  emojiPickerRef.value = picker;
  const emojiContainer = document.getElementById('emoji');
  emojiContainer.appendChild(picker);

  picker.addEventListener('emoji-click', handleEmojiClick);
  picker.addEventListener('skin-tone-change', handleSkinChange);


  if (attrs.style) {
    const style = document.createElement('style');
    style.textContent = `:host{--num-columns:10 } margin:100px 0`
    picker.shadowRoot.appendChild(style);
  }

});

onUnmounted(() => {
  if (emojiPickerRef.value) {
    emojiPickerRef.value.removeEventListener('emoji-click', handleEmojiClick);
    emojiPickerRef.value.removeEventListener('skin-tone-change', handleSkinChange);
  }
});

if (props.isDataBase) {
  const db = new Database({
    dataSource: props.dataSource,
    locale: props.locale,
  });
  database.value = db;
}

defineExpose({
  database,
  emojiPickerRef,
});


</script>

<style lang="scss" scoped>
#emoji {
  display: inline-block
}
</style>

<!-- scope 只能作用于静态模板上 -->
<style lang="scss">
emoji-picker {
  width: v-bind('props.width');
  height: v-bind('props.height');
}
</style>
